package com.zfk.framework.config;

import com.zfk.framework.models.config.Config;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.LoaderOptions;

import java.io.FileInputStream;
import java.io.IOException;

public class ConfigLoader {
    public static final Logger logger = LogManager.getLogger(ConfigLoader.class);
    public static Config config;//类变量，充当缓存，全局访问，简单 单例模式


    /**
     * 加载配置文件
     *
     * @param configFilePath 配置文件路径
     * @return 配置对象
     */
    public static Config loadConfig(String configFilePath) {
        if (config != null) {
            logger.info("配置信息已加载，返回应存在的{}", config);
            return config;
        }
        LoaderOptions loaderOptions = new LoaderOptions();
        Yaml yaml = new Yaml(new Constructor(Config.class, loaderOptions));
        try (FileInputStream fls = new FileInputStream(configFilePath)) {
            config = yaml.load(fls);
            if (config == null) {
                logger.error("配置文件{}为空，请填写内容", configFilePath);
                throw new RuntimeException("配置文件不能为空");
            }
        } catch (IOException e) {
            logger.error("配置文件{}加载失败", configFilePath);
            throw new RuntimeException("配置文件" + configFilePath + "加载失败" + e.getMessage(), e);
        }
        logger.info("配置文件{}加载成功", configFilePath);
        return config;
    }

    public static Config getConfig() {
        if (config == null) {
            logger.info("配置文件未初始化，请调用ConfigLoader.loadConfig方法初始化");
            }
        return config;
    }

}
